package com.example.demo.controller;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    private static final String KEY = "crud-users";

    @Autowired
    private UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String login(String username, String password) {
        User user = userMapper.selectByUsernameAndPassword(username, password);
        if (user == null) {
            return "failed";
        }
        return "success";
    }

    /**
     * 查询所有的用户信息
     * 缓存到redis
     * @return
     */
    @GetMapping
    public List<User> findAll() {
        // 1. 根据key查询redis数据库
        String jsonArrayStr = stringRedisTemplate.opsForValue().get(KEY);
        List<User> users;
        //2. 看从redis里面查询出来的数据有没有，如果存在，则解析成List数据后直接返回，如果不存在，则从mysql数据库查询
        if (StrUtil.isNotBlank(jsonArrayStr)) {
            // 3. 对查询出来的json字符串进行解析
            users = JSONUtil.toBean(jsonArrayStr, new TypeReference<List<User>>() {
            }, true);
            log.info("======查询redis");
        } else {
            log.info("======查询数据库");
            //查询数据库
            users = userMapper.selectAll();
            // 4. 从数据库查询出来的数据要记得缓存到redis里面，方便下次查询
            stringRedisTemplate.opsForValue().set(KEY, JSONUtil.toJsonStr(users));
        }
        return users;
    }
}
